<template>
  <div class="stomp-container">
    <el-row class="stomp-item" :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="sendGreeting()">发送</el-button>
      </el-col>
    </el-row>
    <el-row class="stomp-item" :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="sendChannel()">发送给用户服务</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import Websocket from '@/api/websocket'

export default {
  name: 'Stomp',
  data() {
    return {
      stompClient: null
    }
  },
  computed: {},
  created() {
    const socket = new SockJS(Websocket.stompAddr) // 路径
    // const socket = new SockJS('http://127.0.0.1:9999/bonelf/support/ws') // 路径
    this.stompClient = Stomp.over(socket)
    const headers = {}
    this.stompClient.connect(
      headers,
      (frame) => {
        // 连接
        console.log('frame', frame)
        this.stompClient.subscribe(
          '/topic/greeting',
          (greeting) => {
            console.log('greeting', greeting.body)
          },
          headers
        )
      },
      (err) => {
        console.log('失败')
        console.log(err)
      }
    )
  },
  methods: {
    sendGreeting() {
      const headers = {}
      console.log('sendGreeting')
      if (this.stompClient) {
        this.stompClient.send('/app/greeting', headers, JSON.stringify({ msg: 'hello' }))
      }
    },
    sendChannel() {
      const headers = { userId: 1 }
      console.log('sendChannel')
      if (this.stompClient) {
        this.stompClient.send('/app/user/greeting', headers, JSON.stringify({ cmdId: '1', data: { msg: 'hello' }}))
      }
    }
  }
}
</script>

<style>

.stomp-container {
  padding:0 50px;
}

.stomp-item{
  margin-top: 50px;
}

</style>
